<?php

namespace app\api\controller;

use app\model\zs\ZsMemberMedia;
use think\facade\Filesystem;
use think\file\UploadedFile;

/**
 * 小程序种草API
 * Class ArticleMedia
 * @package app\api\controller
 */
class ArticleMedia
{
    private $filesystem;
    private $baseUrl;

    public function __construct()
    {
        $disk_type = 'public';
        $config_disks = config('filesystem.disks');
        $disk_url = ltrim($config_disks[$disk_type]['url'], '/');

        $this->filesystem = Filesystem::disk($disk_type);
        $this->baseUrl = "";
    }

    /**
     * 上传图片：
     * 1.检测文件大小和类型
     * 2.调用微信接口检测图片合法性
     * 3.最终上传到本地服务器
     */
    public function upload()
    {
        $file = request()->file('file');
        $vipcode = request()->param('vipcode');

        $result_validate = $this->validateUpload();
        if ($result_validate['err']) {
            return jsonData(0, $result_validate['msg']);
        }

        $dir = 'mini_article';
        // putFile 返回的是相对于 filesystem.php 配置的 root 字段的路径，并且前面不带 /
        $savepath = $this->filesystem->putFile($dir, $file);

        $model_media = $this->insertMedia($file, $vipcode, $savepath);

        $media_id = $model_media->id;
        $media_url = $model_media->url;
        return jsonData(1, '成功', compact('media_id', 'media_url'));
    }

    /**
     * 图片记录插入数据表
     */
    private function insertMedia(UploadedFile $file, $vipcode, $savepath)
    {
        $pathname = $file->getPathname();
        $imagesize = @getimagesize($pathname);
        $width = $imagesize[0] ?? 0;
        $height = $imagesize[1] ?? 0;

        $model_media = new ZsMemberMedia();
        $model_media->vipcode = $vipcode;
        $model_media->url = $this->baseUrl . '/' . $savepath;
        $model_media->path = $savepath;
        $model_media->raw = $file->getOriginalName();
        $model_media->size = $file->getSize();
        $model_media->width = $width;
        $model_media->height = $height;
        $model_media->save();
        return $model_media;
    }

    /**
     * 上传验证
     */
    private function validateUpload()
    {
        $max_size = 1024*1024*3; // 单位字节，这里表示最大1MB
        $request = request()->file();
        $rules = [
            'file' => [
                'file',
                'fileSize:' . $max_size,
                'image',
                // 'fileExt:jpg',
            ],
        ];
        $messages = [
            'file.file' => '必须上传文件',
            'file.fileSize' => '文件大小不能超过 3MB',
            'file.image' => '必须上传图片',
            // 'file.fileExt' => '图片文件后缀不合法',
        ];
        try {
            validate($rules, $messages)->check($request);
        } catch (\think\exception\ValidateException $e) {
            return ['err' => true, 'msg' => $e->getMessage()];
        }
        return ['err' => false];
    }

    // TODO:调用微信imgSecCheck接口检测图片违规
    // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.imgSecCheck.html
    private function wechatImgSecCheck()
    {
    }
}
